<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规则名称" prop="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          placeholder="请输入规则名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="参数名称" prop="paramName">
        <el-select v-model="queryParams.paramName" placeholder="请选择参数名称" clearable>
          <el-option label="电压" value="voltage" />
          <el-option label="电流" value="current" />
          <el-option label="功率" value="power" />
          <el-option label="电能" value="energy" />
          <el-option label="功率因数" value="power_factor" />
          <el-option label="频率" value="frequency" />
          <el-option label="温度" value="temperature" />
        </el-select>
      </el-form-item>
      <el-form-item label="告警级别" prop="alarmLevel">
        <el-select v-model="queryParams.alarmLevel" placeholder="请选择告警级别" clearable>
          <el-option label="紧急" value="1" />
          <el-option label="重要" value="2" />
          <el-option label="一般" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['energy:alarm:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['energy:alarm:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="alarmRuleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="规则名称" align="center" prop="ruleName" :show-overflow-tooltip="true" />
      <el-table-column label="设备名称" align="center" prop="deviceName" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.deviceName">{{ scope.row.deviceName }}</span>
          <span v-else style="color: #999;">全局规则</span>
        </template>
      </el-table-column>
      <el-table-column label="参数名称" align="center" prop="paramLabel" />
      <el-table-column label="条件" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.conditionType === '1'">大于 {{ scope.row.thresholdMin }}</span>
          <span v-if="scope.row.conditionType === '2'">小于 {{ scope.row.thresholdMin }}</span>
          <span v-if="scope.row.conditionType === '3'">等于 {{ scope.row.thresholdMin }}</span>
          <span v-if="scope.row.conditionType === '4'">{{ scope.row.thresholdMin }} ~ {{ scope.row.thresholdMax }}</span>
        </template>
      </el-table-column>
      <el-table-column label="告警级别" align="center" prop="alarmLevel">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.alarmLevel === '1'" type="danger">紧急</el-tag>
          <el-tag v-if="scope.row.alarmLevel === '2'" type="warning">重要</el-tag>
          <el-tag v-if="scope.row.alarmLevel === '3'" type="info">一般</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['energy:alarm:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['energy:alarm:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改告警规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="设备" prop="deviceId">
          <el-select v-model="form.deviceId" placeholder="请选择设备(可选)" clearable>
            <el-option
              v-for="device in deviceOptions"
              :key="device.deviceId"
              :label="device.deviceName"
              :value="device.deviceId"
            />
          </el-select>
          <div style="color: #999; font-size: 12px; margin-top: 5px;">
            不选择设备时为全局规则，适用于所有设备
          </div>
        </el-form-item>
        <el-form-item label="参数名称" prop="paramName">
          <el-select v-model="form.paramName" placeholder="请选择参数名称">
            <el-option label="电压" value="voltage" />
            <el-option label="电流" value="current" />
            <el-option label="功率" value="power" />
            <el-option label="电能" value="energy" />
            <el-option label="功率因数" value="power_factor" />
            <el-option label="频率" value="frequency" />
            <el-option label="温度" value="temperature" />
          </el-select>
        </el-form-item>
        <el-form-item label="条件类型" prop="conditionType">
          <el-select v-model="form.conditionType" placeholder="请选择条件类型">
            <el-option label="大于" value="1" />
            <el-option label="小于" value="2" />
            <el-option label="等于" value="3" />
            <el-option label="区间" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="阈值下限" prop="thresholdMin" v-if="form.conditionType">
          <el-input-number v-model="form.thresholdMin" :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="阈值上限" prop="thresholdMax" v-if="form.conditionType === '4'">
          <el-input-number v-model="form.thresholdMax" :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="告警级别" prop="alarmLevel">
          <el-select v-model="form.alarmLevel" placeholder="请选择告警级别">
            <el-option label="紧急" value="1" />
            <el-option label="重要" value="2" />
            <el-option label="一般" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAlarmRule, getAlarmRule, delAlarmRule, addAlarmRule, updateAlarmRule, changeAlarmRuleStatus } from "@/api/energy/alarm";
import { listDevice } from "@/api/energy/device";

export default {
  name: "AlarmRule",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 告警规则表格数据
      alarmRuleList: [],
      // 设备选项
      deviceOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleName: null,
        paramName: null,
        alarmLevel: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ruleName: [
          { required: true, message: "规则名称不能为空", trigger: "blur" }
        ],
        paramName: [
          { required: true, message: "参数名称不能为空", trigger: "change" }
        ],
        conditionType: [
          { required: true, message: "条件类型不能为空", trigger: "change" }
        ],
        thresholdMin: [
          { required: true, message: "阈值不能为空", trigger: "blur" }
        ],
        alarmLevel: [
          { required: true, message: "告警级别不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDeviceOptions();
  },
  methods: {
    /** 查询告警规则列表 */
    getList() {
      this.loading = true;
      listAlarmRule(this.queryParams).then(response => {
        this.alarmRuleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取设备选项 */
    getDeviceOptions() {
      listDevice({ status: '0' }).then(response => {
        this.deviceOptions = response.rows || [];
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ruleId: null,
        ruleName: null,
        deviceId: null,
        paramName: null,
        conditionType: null,
        thresholdMin: null,
        thresholdMax: null,
        alarmLevel: null,
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ruleId)
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加告警规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ruleId = row.ruleId || this.ids
      getAlarmRule(ruleId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改告警规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ruleId != null) {
            updateAlarmRule(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAlarmRule(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ruleIds = row.ruleId || this.ids;
      this.$modal.confirm('是否确认删除告警规则编号为"' + ruleIds + '"的数据项？').then(function() {
        return delAlarmRule(ruleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.ruleName + '"规则吗？').then(function() {
        return changeAlarmRuleStatus(row.ruleId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    }
  }
};
</script> 